#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QFileDialog"
#include "QFile"
#include "driver.c"

using namespace std;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_buttonMorphology_clicked()
{
    ui->stackedWidget->setCurrentIndex(0);
}

void MainWindow::on_buttonGrammar_clicked()
{
    ui->stackedWidget->setCurrentIndex(1);
}

void MainWindow::on_buttonSemantics_clicked()
{
    ui->stackedWidget->setCurrentIndex(2);
}

void MainWindow::on_buttonCode_clicked()
{
    ui->stackedWidget->setCurrentIndex(3);
}

void MainWindow::on_actionExit_triggered()
{
    close();
}

void MainWindow::on_actionOpen_triggered()
{
    ui->morphologyInput->clear();
    ui->morphologyOutput->clear();
    ui->grammarInput->clear();
    ui->morphologyOutput->clear();
    QString path = QFileDialog::getOpenFileName(this, tr("Open File"), "/home", tr("Text files(*)"));
    QFile fileQS(path);
    if (!fileQS.open(QIODevice::ReadOnly))
        return;
    while (!fileQS.atEnd())
    {
        QString line = fileQS.readLine();
        ui->morphologyInput->insertPlainText(line);
        ui->grammarInput->insertPlainText(line);
    }
    fileQS.close();

    QByteArray ba = path.toLatin1();
    char* ch = ba.data();
    lexer_driver(ch);
    parser_driver(ch);
    QFile fileLexer("lexer.out");
    if (!fileLexer.open(QIODevice::ReadOnly))
        return;
    while (!fileLexer.atEnd())
    {
        QString line = fileLexer.readLine();
        ui->morphologyOutput->insertPlainText(line);
    }
    fileLexer.close();
    QFile fileParser("parser.out");
    if (!fileParser.open(QIODevice::ReadOnly))
        return;
    while (!fileParser.atEnd())
    {
        QString line = fileParser.readLine();
        ui->grammarOutput->insertPlainText(line);
    }
    fileParser.close();
}
